<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="Delete strategy"
    @ok="handleSubmit"
    :closeFunc="handleClose"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { defineEmits } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { deleteTelemetrySchemas } from './deleteModal.data';
  import { ref } from 'vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { isArray } from '@vue/shared';

  const emit = defineEmits(['success']);
  const keyName = ref<string>('');
  const mode = ref<string>('');
  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async ({ key, mode: _mode }) => {
      keyName.value = isArray(key) ? key.join(',') : key;
      mode.value = _mode;
      setModalProps({
        ...modalStyleSetting,
      });
    },
  );
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    layout: 'vertical',
    schemas: deleteTelemetrySchemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const handleClose = async () => {
    resetFields();
    return true;
  };

  const handleSubmit = async () => {
    setModalProps({ confirmLoading: true });
    try {
      const values = await validate();
      closeModal();
      emit('success', {
        key: mode.value,
        keys: keyName.value,
        values: { ...values },
      });
      resetFields();
      setFieldsValue({ deleteStrategy: 'DeleteAllData' });
    } catch (e) {}
    setModalProps({ confirmLoading: false });
  };
</script>
